package com.example.redislearning.controller;

import com.example.redislearning.dto.ApiResponse;
import com.example.redislearning.service.RateLimitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 限流控制控制器
 * 提供限流相关的REST API接口
 */
@RestController
@RequestMapping("/api/rate-limit")
@CrossOrigin(origins = "*")
public class RateLimitController {

    @Autowired
    private RateLimitService rateLimitService;

    /**
     * 检查API调用是否被限流
     */
    @GetMapping("/check-api")
    public ApiResponse<Boolean> checkApiRateLimit(
            @RequestParam String apiKey,
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "100") int maxRequests,
            @RequestParam(defaultValue = "60") int timeWindow) {
        
        boolean isLimited = rateLimitService.isApiRateLimited(apiKey, userId, maxRequests, timeWindow);
        
        if (isLimited) {
            return ApiResponse.error("API调用过于频繁，请稍后重试");
        }
        
        return ApiResponse.success(false);
    }

    /**
     * 检查用户行为是否被限流
     */
    @GetMapping("/check-action")
    public ApiResponse<Boolean> checkUserActionRateLimit(
            @RequestParam String action,
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "10") int maxActions,
            @RequestParam(defaultValue = "60") int timeWindow) {
        
        boolean isLimited = rateLimitService.isUserActionRateLimited(action, userId, maxActions, timeWindow);
        
        if (isLimited) {
            return ApiResponse.error("用户行为过于频繁，请稍后重试");
        }
        
        return ApiResponse.success(false);
    }

    /**
     * 获取API剩余调用次数
     */
    @GetMapping("/remaining-api")
    public ApiResponse<Integer> getApiRemainingRequests(
            @RequestParam String apiKey,
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "100") int maxRequests,
            @RequestParam(defaultValue = "60") int timeWindow) {
        
        int remaining = rateLimitService.getApiRemainingRequests(apiKey, userId, maxRequests, timeWindow);
        return ApiResponse.success(remaining);
    }

    /**
     * 获取用户行为剩余次数
     */
    @GetMapping("/remaining-action")
    public ApiResponse<Integer> getUserActionRemaining(
            @RequestParam String action,
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "10") int maxActions,
            @RequestParam(defaultValue = "60") int timeWindow) {
        
        int remaining = rateLimitService.getUserActionRemaining(action, userId, maxActions, timeWindow);
        return ApiResponse.success(remaining);
    }

    /**
     * 重置API限流计数
     */
    @PostMapping("/reset-api")
    public ApiResponse<Boolean> resetApiRateLimit(
            @RequestParam String apiKey,
            @RequestParam Integer userId) {
        
        boolean success = rateLimitService.resetApiRateLimit(apiKey, userId);
        return ApiResponse.success(success);
    }

    /**
     * 重置用户行为限流计数
     */
    @PostMapping("/reset-action")
    public ApiResponse<Boolean> resetUserActionRateLimit(
            @RequestParam String action,
            @RequestParam Integer userId) {
        
        boolean success = rateLimitService.resetUserActionRateLimit(action, userId);
        return ApiResponse.success(success);
    }

    /**
     * 获取限流统计信息
     */
    @GetMapping("/info")
    public ApiResponse<String> getRateLimitInfo(
            @RequestParam String apiKey,
            @RequestParam Integer userId) {
        
        String info = rateLimitService.getRateLimitInfo(apiKey, userId);
        return ApiResponse.success(info);
    }

    /**
     * 配置限流规则
     */
    @PostMapping("/configure")
    public ApiResponse<Boolean> configureRateLimit(
            @RequestParam String apiKey,
            @RequestParam int maxRequests,
            @RequestParam int timeWindow,
            @RequestParam(defaultValue = "10") int burstSize) {
        
        boolean success = rateLimitService.configureRateLimit(apiKey, maxRequests, timeWindow, burstSize);
        return ApiResponse.success(success);
    }

    /**
     * 检查IP是否被限流
     */
    @GetMapping("/check-ip")
    public ApiResponse<Boolean> checkIpRateLimit(
            @RequestParam String ipAddress,
            @RequestParam(defaultValue = "1000") int maxRequests,
            @RequestParam(defaultValue = "3600") int timeWindow) {
        
        boolean isLimited = rateLimitService.isIpRateLimited(ipAddress, maxRequests, timeWindow);
        
        if (isLimited) {
            return ApiResponse.error("IP地址请求过于频繁，请稍后重试");
        }
        
        return ApiResponse.success(false);
    }

    /**
     * 全局API限流检查
     */
    @GetMapping("/check-global")
    public ApiResponse<Boolean> checkGlobalApiRateLimit(
            @RequestParam String apiKey,
            @RequestParam(defaultValue = "10000") int maxRequests,
            @RequestParam(defaultValue = "3600") int timeWindow) {
        
        boolean isLimited = rateLimitService.isGlobalApiRateLimited(apiKey, maxRequests, timeWindow);
        
        if (isLimited) {
            return ApiResponse.error("全局API调用过于频繁，请稍后重试");
        }
        
        return ApiResponse.success(false);
    }

    /**
     * 获取当前限流状态
     */
    @GetMapping("/status")
    public ApiResponse<Map<String, Object>> getCurrentRateLimitStatus(
            @RequestParam String apiKey,
            @RequestParam Integer userId) {
        
        Map<String, Object> status = rateLimitService.getCurrentRateLimitStatus(apiKey, userId);
        return ApiResponse.success(status);
    }

    /**
     * 动态调整限流阈值
     */
    @PostMapping("/adjust")
    public ApiResponse<Boolean> adjustRateLimitThreshold(
            @RequestParam String apiKey,
            @RequestParam int newMaxRequests,
            @RequestParam int newTimeWindow) {
        
        boolean success = rateLimitService.adjustRateLimitThreshold(apiKey, newMaxRequests, newTimeWindow);
        return ApiResponse.success(success);
    }

    /**
     * 清理过期的限流数据
     */
    @PostMapping("/cleanup")
    public ApiResponse<String> cleanupExpiredRateLimitData() {
        rateLimitService.cleanupExpiredRateLimitData();
        return ApiResponse.success("限流数据清理完成");
    }
}